﻿/****************************** Module Header ******************************\
 * Module Name:  ExMethodForFileUpload.cs
 * Module Version:  1.0.0 (2011-9-30)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used to extension webcontrol instance's method.  It supplies 
 * public static extension methods to load data or get othor control.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;

namespace UCL.Web
{
    /// <summary>
    /// FileUpload服务器控件的扩展方法
    /// </summary>
    public static class ExMethodForFileUpload
    {
        /// <summary>
        /// 检测文件类型是否合法
        /// <para>image=.jpg.png.gif.bmp.psd.ico.tiff.</para>
        /// <para>doc=.txt.rtf.doc.docx.xls.xlsx.ppt.pptx.zip.rar.wps.</para>
        /// <para>file=.jpg.png.gif.bmp.psd.ico.tiff.txt.rtf.doc.docx.xls.xlsx.ppt.pptx.zip.rar.wps.</para>
        /// </summary>
        /// <param name="ext">待检测的文件类型，如 .gif</param>
        /// <param name="extFilter"></param>
        /// <returns></returns>
        public static bool CheckAllowExtension(string ext, string extFilter = "image")
        {
            if (extFilter == "all") return true;
            string sExt = "";
            switch (extFilter.ToLower())
            {
                case "image":
                    sExt = ".jpg.png.gif.bmp.psd.ico.tiff.";
                    break;
                case "doc":
                    sExt = ".txt.rtf.doc.docx.xls.xlsx.ppt.pptx.zip.rar.wps.";
                    break;
                case "file":
                    sExt = ".jpg.png.gif.bmp.psd.ico.tiff.txt.rtf.doc.docx.xls.xlsx.ppt.pptx.zip.rar.wps.";
                    break;
            }
            return sExt.IndexOf(ext.ToLower() + ".") == -1 ? false : true;
        }

        /// <summary>
        /// 检测是否是有效的图片文件 [2013-7-12 by sutroon]
        /// </summary>
        /// <param name="fu"></param>
        /// <returns></returns>
        public static bool IsImage(this FileUpload fu)
        {
            if (!fu.HasFile) return false;
            return CheckAllowExtension(Path.GetExtension(fu.FileName));
        }

        /// <summary>
        /// 上传文件
        /// <para>建议路径模板为:根目录/模块名称/日期模板/</para>
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <param name="uploadPath">路径模板
        ///     <para>/root/{yyyy}/{MM}/{dd}/ = /root/2012/02/08/</para>
        /// </param>
        /// <param name="extFilter">限制文件类型，防止黑客攻击</param>
        /// <param name="autoNamed"></param>
        /// <returns></returns>
        public static string UploadFile(this FileUpload fileUpload, string uploadPath = "/Upload", string extFilter = "image", bool autoNamed = true)
        {
            if (fileUpload == null || !fileUpload.HasFile) return "";
            // EncryptHelper.MD5(fileUpload.FileName).ToArray(4).ToString("/")
            if (string.IsNullOrEmpty(uploadPath)) uploadPath = "/Upload";
            uploadPath = "{0}/{1}".Fmt(uploadPath, DateTime.Now.ToString("yyyy/MM/dd"));

            string strFile = fileUpload.FileName;
            string strExt = Path.GetExtension(strFile);

            if (!CheckAllowExtension(strExt, extFilter)) return "";

            if (!uploadPath.EndsWith("/")) uploadPath += "/";
            string sDir = HttpContext.Current.Server.MapPath(uploadPath);
            if (!Directory.Exists(sDir)) Directory.CreateDirectory(sDir);
            StringBuilder sbName = new StringBuilder();
            Random rnd = new Random();
            sbName.Append(DateTime.Now.ToString("yyyyMMddHHmmss"));
            sbName.Append(rnd.Next(999));
            sbName.Append(strExt);
            if (autoNamed) strFile = sbName.ToString();
            strFile = uploadPath + strFile;
            fileUpload.SaveAs(HttpContext.Current.Server.MapPath(strFile));
            return strFile;
        }

        /// <summary>
        /// 上传文件数据
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <param name="extFilter"></param>
        /// <returns></returns>
        public static byte[] UploadFileData(this FileUpload fileUpload, string extFilter = "image")
        {
            if (!fileUpload.HasFile) return null;
            string strExt = Path.GetExtension(fileUpload.FileName);
            if (!CheckAllowExtension(extFilter, strExt)) return null;

            Stream stm = fileUpload.PostedFile.InputStream;
            byte[] byteImg = new byte[stm.Length];
            stm.Read(byteImg, 0, byteImg.Length);
            stm.Close();
            return byteImg;
        }
    }
}
